package logic

import (
	"context"
	"errors"
	"user/common"
	"user/models"

	"user/internal/svc"
	"user/pb/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserLogic {
	return &UpdateUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// UpdateUser 更新用户
func (l *UpdateUserLogic) UpdateUser(in *user.UserInfo) (*user.Empty, error) {
	u, err := l.svcCtx.UserModel.FindOne(l.ctx, in.Id)
	if err != nil {
		return nil, err
	}

	if u.Status == common.UserStatusDisabled {
		return nil, errors.New("用户已禁用, 不可修改信息")
	}

	newUser := &models.User{Id: in.Id}
	if in.Name != "" {
		newUser.Name = in.Name
	}
	if in.Email != "" {
		newUser.Email = in.Email
	}
	if in.Mobile != "" {
		newUser.Mobile = in.Mobile
	}
	if in.Avatar != "" {
		newUser.Avatar = in.Avatar
	}
	if in.Password != "" {
		newUser.Password = common.Md5Encrypt(in.Password)
	}
	err = l.svcCtx.UserModel.Update(l.ctx, newUser)
	if err != nil {
		return nil, err
	}
	return &user.Empty{}, nil
}
